package com.esunrising.esungsc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esunrising.esungsc.common.utils.ESUNGSCUtil;
import com.esunrising.esungsc.common.utils.HttpUtil;
import com.esunrising.esungsc.config.GSCAPIConfig;
import com.esunrising.esungsc.dao.KMTXDao;
import com.esunrising.esungsc.entity.TApiKmtx;
import com.esunrising.esungsc.service.KMTXService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class KMTXServiceImpl extends BaseServiceImpl<KMTXDao, TApiKmtx> implements KMTXService {

    @Resource
    private GSCAPIConfig gscapiConfig;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private KMTXDao kmtxDao;

    @Override
    public List<TApiKmtx> getKMTXResult(String year) {
        //获取模块的 url
        String baseUrl = gscapiConfig.getBaseUrl();
        String getBfChartOfAccount = gscapiConfig.getApis().get("getBfChartOfAccount");
        System.out.println("api接口 = " + getBfChartOfAccount);
        String url = baseUrl + getBfChartOfAccount;
        System.out.println("url == "+url);

        //添加query参数
        String queryParam = HttpUtil.putQueryParam(url, null);

        //设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.addAll(new LinkedMultiValueMap<>(gscapiConfig.getRequestHeaders()));

        //设置请求体
        HashMap<String,Object> httpBody = new HashMap<>();
        httpBody.put("year", year);

        //组织参数
        HttpEntity<Map<String,Object>> httpEntity = new HttpEntity<>(httpBody, httpHeaders);

        //发送请求
        ResponseEntity<String> response = restTemplate.exchange(queryParam, HttpMethod.POST, httpEntity,String.class);

        System.out.println("请求返回结果response == "+response);

        //分析结果
        if (response.getStatusCodeValue() == 200){
            String responseBody = response.getBody();
            System.out.println("返回体 == "+responseBody);
//            return parseKMTXResult(responseBody);
            return parseKMTXResult2(responseBody);
        }else {

            System.out.println(response.getStatusCode());
            System.out.println(response.getStatusCodeValue());
            System.out.println(response.getHeaders());
            System.out.println(response.getBody());
            return null;
        }
    }

    @Override
    public void saveKmtx(List<TApiKmtx> kmtxList) {
        for (TApiKmtx kmtxs: kmtxList){
            System.out.println("科目体系列表 = " + kmtxs);
            kmtxDao.save(kmtxs);
        }
    }

    public List<TApiKmtx> parseKMTXResult(String responseBody) {
        JSONObject jsonObject = JSON.parseObject(responseBody);
        Boolean result = jsonObject.getBoolean("result");
        String code = jsonObject.getString("code");
        if (result){
            log.info("请求科目体系数据成功");
            JSONArray value = jsonObject.getJSONArray("value");
            System.out.println("value = " + value);

            ArrayList<TApiKmtx> kmtxList = new ArrayList<>();

            for (int i = 0; i < value.size(); i++){
                String s = value.getString(i);


                JSONObject jO = JSONObject.parseObject(s);
                JSONArray valueArray = jsonObject.getJSONArray("value");

                for (int j = 0; j < valueArray.size(); j++) {
                    JSONObject item = valueArray.getJSONObject(i);
                    JSONArray listAccTitleProp = item.getJSONArray("listAccTitleProp");
                    if (listAccTitleProp.size() > 0) {
                        JSONObject firstItem = listAccTitleProp.getJSONObject(0);
                        System.out.println(">>>>>"+firstItem.toString());
                    }
                }

                boolean listAccTitleProp1 = s.equals("listAccTitleProp");
               // boolean listAccTitleProp = value.equals("listAccTitleProp");
                if (listAccTitleProp1) {

                    JSONObject json = value.getJSONObject(i);

                    TApiKmtx tApiKmtx = ESUNGSCUtil.jsonObject2ApiKmtx(json);
                    kmtxList.add(tApiKmtx);
                }
            }
            return kmtxList;
        }else {
            log.error("请求科目体系数据失败");
            return null;
        }
    }

    private List<TApiKmtx> parseKMTXResult2(String responseBody) {
        JSONObject jsonObject = JSON.parseObject(responseBody);
        Boolean result = jsonObject.getBoolean("result");
        String code = jsonObject.getString("code");
        if (result){
            log.info("请求科目体系数据成功");
            JSONArray value = jsonObject.getJSONArray("value");
            System.out.println("value = " + value);

            ArrayList<TApiKmtx> kmtxList = new ArrayList<>();

            for (int i = 0; i < value.size(); i++){

                JSONObject item = value.getJSONObject(i);
                System.out.println("单个value值：："+item);
                // 处理科目属性
                JSONArray listAccTitleProp = item.getJSONArray("ChartOfAccount");

                for (int index = 0; index < listAccTitleProp.size(); index++) {
                    JSONObject json = listAccTitleProp.getJSONObject(index);
                    System.out.println(">>>>>"+json.toString());
                    TApiKmtx tApiKmtx = ESUNGSCUtil.jsonObject2ApiKmtx(json);
                    kmtxList.add(tApiKmtx);
                }
                // 处理科目体系
//                JSONArray ChartOfAccount = item.getJSONArray("ChartOfAccount");
//
//                for (int index = 0; index < ChartOfAccount.size(); index++) {
//                    JSONObject json = ChartOfAccount.getJSONObject(index);
//                    TApiKmsx tApiKmsx = ESUNGSCUtil.jsonObject2ApiKmsx(json);
//                    kmsxList.add(tApiKmsx);
//                }

            }
            return kmtxList;
        }else {
            log.error("请求科目体系数据失败");
            return null;
        }
    }
}
